// 首先是reduce的使用场景和使用方法

// 1. 对数组的累加
const testArray1 = [1, 2, 3, 4, 5, 6, 7];
const result1 = testArray1.reduce((pre, cur) => {
  return pre + cur;
}, 0);
console.log("result1 ", result1);

// 2. 将数组对象转成对象
const testArray2 = [
  { name: "tom", value: 20 },
  { name: "tom1", value: 21 },
  { name: "tom2", value: 22 },
];
const result2 = testArray2.reduce((pre, cur) => {
  pre[cur.name] = cur.value;
  return pre;
}, {});

console.log("result2 ", result2);

// 3. 进行数据分组
const testArray3 = [
  { name: "tom1", value: 20 },
  { name: "tom2", value: 21 },
  { name: "tom3", value: 20 },
];
const result3 = testArray3.reduce((pre, cur) => {
  if (!pre[cur.value]) {
    pre[cur.value] = [cur.name];
  } else {
    pre[cur.value].push(cur.name);
  }
  return pre;
}, {});
console.log(result3);

// 4. 使用reduce来处理异步数组
const testArray4 = [Promise.resolve(1), Promise.resolve(2)];
const result4 = testArray4.reduce(async (pre, cur) => {
  const res1 = await pre;
  const res2 = await cur;
  return res1 + res2;
}, Promise.resolve(0))
result4.then((res) => {
  console.log(res);
}).catch(err => {
  console.log(err);
})
